package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.persistence.CascadeType;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import java.util.Optional;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public CommandLineRunner demo(UserRepository repository, PlatformTransactionManager transactionManager) {
        return args -> {

            //测试CascadeType.MERGE;
//            Department department = new Department();
//            department.setId(9);
//            department.setCode("YXB");
//            department.setName("营销部");
//            User user = new User();
//            user.setDepartment(department);
//            user.setName("zzj");
//            repository.save(user);

            //测试CascadeType.PERSIST;
//            Department department = new Department();
//            department.setCode("YXB");
//            department.setName("营销部");
//            User user = new User();
//            user.setDepartment(department);
//            user.setName("zzj");
//            repository.save(user);

            //测试CascadeType.REMOVE;
//            Department department = new Department();
//            department.setId(9);
//            User user = new User();
//            user.setId(1);
//            user.setDepartment(department);
//            repository.delete(user);

            //测试CascadeType.REFRESH
            DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
            transactionDefinition.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
            TransactionStatus transaction = transactionManager.getTransaction(transactionDefinition);
            Optional<User> byId = repository.findById(1);
            User user = byId.get();
            System.out.println(user);
            repository.refresh(user);
            System.out.println(user);
            transactionManager.commit(transaction);
        };
    }

}
